package com.reuters.rfa.example.omm.gui.viewer;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.UIManager;

import com.reuters.rfa.example.framework.sub.SubAppContext;
import com.reuters.rfa.example.omm.gui.viewer.AppConfig;
import com.reuters.rfa.example.omm.gui.viewer.UserOptions;
import com.reuters.rfa.example.utility.CommandLine;

/**
 * Main class for the Viewer GUI example. This class is responsible for:
 * <ul>
 * <li>Declaring the {@linkplain com.reuters.rfa.example.utility.CommandLine
 * command line options}
 * <li>Creating the {@link com.reuters.rfa.example.framework.sub.SubAppContext
 * SubAppContext}
 * <li>Creating the {@link ViewerPanel}
 * </ul>
 * 
 */
public class Viewer
{
    public void init()
    {
        _appContext = SubAppContext.create(System.out);
        _appContext.setAutoDictionaryDownload();
        initGUI();
    }

    protected void initGUI()
    {
        // initLookAndFeel
        // font
        int fontSize = CommandLine.intVariable("fontSize");
        String fontName = CommandLine.variable("font");
        Font font = new Font(fontName, Font.PLAIN, fontSize);
        UIManager.put("List.font", font);
        UIManager.put("Label.font", font);
        UIManager.put("TextField.font", font);
        UIManager.put("TextArea.font", font);
        UIManager.put("ComboBox.font", font);
        UIManager.put("CheckBox.font", font);
        UIManager.put("Table.font", font);
        UIManager.put("TableHeader.font", font);
        UIManager.put("Button.font", font);
        UIManager.put("TabbedPane.font", font);
        UIManager.put("ToolTip.font", font);

        // background
        Color c = UIManager.getColor("Panel.background");
        UIManager.put("TextArea.background", c);
        UIManager.put("Table.background", c);
        UIManager.put("TabbedPane.background", c);
        UIManager.put("ScrollPane.background", c);

        // foreground
        UIManager.put("Label.foreground", Color.black);

        // create second tab panel
        _display = new ViewerPanel(_appContext);
        _appContext.setCompletionClient(_display);

        final JFrame appFrame = new JFrame("RFA Java OMM Viewer");
        
        appFrame.getContentPane().add("Center", _display.component());

        appFrame.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                cleanup();
                appFrame.setVisible(false);
                appFrame.dispose();
                System.exit(0);
            }
        });
        appFrame.pack();
        int dim = fontSize * 36;
        appFrame.setSize(new Dimension(dim * 2, dim));
        appFrame.setVisible(true);

    }

    void run()
    {
        _appContext.runAwt();
    }

    public static void addCommandLineOptions(UserOptions userOptions) 
    {
        SubAppContext.addCommandLineOptions();
        
        CommandLine.addOption(
                "session", userOptions.getSessionName(), 
                "Sets the consumer session. The default is myNamespace::myOMMViewSession.");

        CommandLine.addOption(
                "fontSize", userOptions.getDialogFontSize(), 
                "font sizeSets the display's font size. The default is 12.");

        CommandLine.addOption(
                "font", userOptions.getDialogFont(), 
                "Sets the font name (or logical font name). The default is the logical font name Monospaced.");

        CommandLine.addOption(
                "sort", userOptions.getSortable(), 
                "Sets whether to support sorting with JDK 1.6 or later (does not perform well for large tables). The default is false.");

        CommandLine.addOption(
                "user", userOptions.getUserName(), 
                "Sets the DACS username for login. The default is the value from the user.name property or guest.");

        CommandLine.addOption(
                "position", userOptions.getPosition(),
                "Sets the DACS position for login. The default is <localhostIPaddr>/net.");

        CommandLine.addOption(
                "application", userOptions.getAppId(), 
                "Sets the DACS application ID for login. The default is 256.");

        CommandLine.addOption(
                "requestPARSupport", userOptions.getSupportPauseResume(), 
                "Sets whether to encode the login request with SupportPauseResume = 1. The default is true.");

        CommandLine.addOption(
                "fileDictionary", !userOptions.getDownloadDicts(), 
                "Sets whether to load the dictionary from file. The default is false.");

        CommandLine.addOption(
                "rdmFieldDictionary", userOptions.getRdmFieldDict(), 
                "Sets the RDMFieldDictionary filename. The default is /var/triarch/RDMFieldDictionary.");

        CommandLine.addOption(
                "enumType", userOptions.getEnumTablesDict(), 
                "Specifies the enumtype.def filename. The default is /var/triarch/enumtype.def.");

        CommandLine.addOption(
                "type", "OMM", 
                "Sets the type of subscriber connection. It can be either OMM or MarketData but for this example, it must be OMM (which is the default setting).");

        CommandLine.addOption(
                "debug", ""+userOptions.getDebugOn(), 
                "Enables debug tracing. The default is false.");

        CommandLine.addOption(
                "consoleOut", userOptions.getOutputToConsole(), 
                "Flag that determines if parsed data is output to the console (default is false).");
        
    }

    public static void main(String argv[])
    {
        // setup the GUI look at feel for this app
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ( ("Windows".equals(info.getName())) || ("Nimbus".equals(info.getName())) ) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Viewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Viewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Viewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Viewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        
        // get the connection config info and user options for the app
        JFrame dummyFrame = new JFrame("");
        UserOptions userOps = new UserOptions();
        
        AppConfig appConfig = new AppConfig(userOps, dummyFrame);
        boolean res = appConfig.getOptions();
        dummyFrame.dispose();

        // if the config was successfully entered
        if (res == true) {
            addCommandLineOptions(userOps);
            CommandLine.setArguments(argv);
            Viewer tableViewer = new Viewer();
            tableViewer.init();
            tableViewer.run();
        }
        else {
            System.exit(1);
        }
    }

    /**
     * Clean up the connection whenever the Applet is stopped (or goes
     * "off-page" in a browser). The service's connection to its data provider
     * is dropped, thus cleaning up valuable browser resources.
     **/
    public void cleanup()
    {
        if (_display != null)
            _display.disable();
    }

    // Static data
    protected static String AppId = "Viewer";

    // Data
    protected SubAppContext _appContext;
    protected ViewerPanel _display;
}
